import { Model, DataTypes } from 'sequelize';
import sequelize from '../db';

/**
 * 登录日志模型
 */
class LoginLog extends Model {
  public id!: string;
  public tenantId?: string;
  public userId?: string;
  public username!: string;
  public loginType!: 'password' | 'sms' | 'wechat' | 'oauth';
  public status!: 'success' | 'failed';
  public ip?: string;
  public ipLocation?: string;
  public userAgent?: string;
  public browser?: string;
  public os?: string;
  public device?: string;
  public failReason?: string;
  public loginTime!: Date;
  public readonly createdAt!: Date;
  public readonly updatedAt!: Date;
}

LoginLog.init(
  {
    id: {
      type: DataTypes.UUID,
      defaultValue: DataTypes.UUIDV4,
      primaryKey: true,
    },
    tenantId: {
      type: DataTypes.UUID,
      allowNull: true,
      field: 'tenant_id',
    },
    userId: {
      type: DataTypes.UUID,
      allowNull: true,
      field: 'user_id',
    },
    username: {
      type: DataTypes.STRING(100),
      allowNull: false,
    },
    loginType: {
      type: DataTypes.ENUM('password', 'sms', 'wechat', 'oauth'),
      allowNull: false,
      defaultValue: 'password',
      field: 'login_type',
    },
    status: {
      type: DataTypes.ENUM('success', 'failed'),
      allowNull: false,
    },
    ip: {
      type: DataTypes.STRING(45),
      allowNull: true,
    },
    ipLocation: {
      type: DataTypes.STRING(200),
      allowNull: true,
      field: 'ip_location',
    },
    userAgent: {
      type: DataTypes.STRING(500),
      allowNull: true,
      field: 'user_agent',
    },
    browser: {
      type: DataTypes.STRING(100),
      allowNull: true,
    },
    os: {
      type: DataTypes.STRING(100),
      allowNull: true,
    },
    device: {
      type: DataTypes.STRING(100),
      allowNull: true,
    },
    failReason: {
      type: DataTypes.STRING(500),
      allowNull: true,
      field: 'fail_reason',
    },
    loginTime: {
      type: DataTypes.DATE,
      allowNull: false,
      field: 'login_time',
    },
  },
  {
    sequelize,
    modelName: 'LoginLog',
    tableName: 'login_logs',
    timestamps: true,
    underscored: true,
  }
);

export default LoginLog;

